//
//  AGLContentView.m
//  滴滴快拍
//
//  Created by dllo on 16/5/19.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "AGLContentView.h"

@interface AGLContentView ()
<
UICollectionViewDelegate,
UICollectionViewDataSource
>

@property (nonatomic, strong) BaseCollectionView *perContentCollection;
@property (nonatomic, strong) NSMutableArray *perContentArr;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) NSTimer *outTimer;

@end

@implementation AGLContentView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self createView];

    }
    return self;

}

- (void)setCategoryId:(NSNumber *)categoryId {
    if (_categoryId != categoryId) {
        _categoryId = categoryId;
    }
    [self createData];

}


#pragma mark 创建每页的内容collection
- (void)createView {

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((self.frame.size.width - 15) / 2, self.frame.size.height / 2.5);
    layout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5);
    layout.minimumLineSpacing = 5;
    layout.minimumInteritemSpacing = 5;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    // 创建collection
    self.perContentCollection = [[BaseCollectionView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) collectionViewLayout:layout];
    [self addSubview:self.perContentCollection];
    //  设置代理
    self.perContentCollection.delegate = self;
    self.perContentCollection.dataSource = self;
    // 注册
    [self.perContentCollection registerClass:[AGLChannelCollectionCell class] forCellWithReuseIdentifier:NSStringFromClass([AGLChannelCollectionCell class])];
    
    [self.perContentCollection registerClass:[AGLTopicCollectionCell class] forCellWithReuseIdentifier:NSStringFromClass([AGLTopicCollectionCell class])];
}

#pragma mark 协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.perContentArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
//    NSLog(@"%@", NSStringFromClass([self.perContentArr[indexPath.item] class]));
    NSString *className = NSStringFromClass([self.perContentArr[indexPath.item] class]);
//    Class class = NSClassFromString(className);
    
//    if ([[class class] isKindOfClass:[AGLChannel class]]) {
    if ([className isEqualToString:@"AGLChannel"]) {

        AGLChannelCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([AGLChannelCollectionCell class]) forIndexPath:indexPath];
        AGLChannel *channel = self.perContentArr[indexPath.item];
        cell.channel = channel;
        
        return cell;

    } else {
        AGLTopicCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([AGLTopicCollectionCell class]) forIndexPath:indexPath];
        AGLTopic *topic = self.perContentArr[indexPath.item];
        cell.topic = topic;
        
        return cell;

    }
    
}

#pragma mark 点击小cell
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *className = NSStringFromClass([self.perContentArr[indexPath.item] class]);
    if ([className isEqualToString:@"AGLChannel"]) {
        AGLChannel *channel = self.perContentArr[indexPath.item];
#pragma mark 视频详情block传值 3.
        // 后一个界面调用block
        self.block(channel.scid, channel.streambase);

        
    } else if ([className isEqualToString:@"AGLTopic"]) {
        AGLTopic *modal = self.perContentArr[indexPath.item];
        if (modal.topicType.integerValue) {
#pragma mark 视频详情block传值channel 3.
            // 后一个界面调用block
            NSString *topicnameStr = [modal.tagtopic componentsSeparatedByString:@"#"][1];
            //            1.url编码
            //            ios中http请求遇到汉字的时候，需要转化成UTF-8，用到的方法是：
            NSString * topicnameEncodingStr = [topicnameStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            //            2.url解码
            //            请求后，返回的数据，如何显示的是这样的格式：%3A%2F%2F，此时需要我们进行UTF-8解码，用到的方法是：
            //            NSString *str = [model.album_name stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

            self.topicBlock(modal.stpid, topicnameEncodingStr);
        } else {
            
            self.topicfaulseBlock(modal.stpid);
        }
        //        NSLog(@"%@ %@", modal.topicType, [modal.topicType class]);
    }

}


- (void)createData {
    
    //1.下拉刷新
    self.perContentCollection.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        self.page = 1;
//        if (_outTimer) {
//            [_outTimer invalidate];
//            _outTimer = nil;
//        }
//        self.outTimer = [NSTimer scheduledTimerWithTimeInterval:10.0f target:self selector:@selector(showNetWorkBad) userInfo:nil repeats:NO];
        [self recieveData];
    }];
    
    //2.上拉加载
    self.perContentCollection.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [self recieveData];
    }];
    // 马上进入刷新状态
    [self.perContentCollection.mj_header beginRefreshing];

}

//-(void)showNetWorkBad{
//    if (_outTimer) {
//        [_outTimer invalidate];
//        _outTimer = nil;
//    }
//    [self.perContentCollection.mj_header endRefreshing];
//}
- (void)recieveData {
    
//    NSString *urlString = [NSString stringWithFormat:@"http://api.miaopai.com/m/cate2_channel.json?os=android&cateid=%@®®&extend=1&udid=0156a9d2-fb05-3001-83e2-e2592b043531&type=news&version=6.3.5&timestamp=1463472565629&unique_id=0156a9d2-fb05-3001-83e2-e2592b043531&per=20&token=&page=1&vend=miaopai", self.categoryId];
//    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    //http://api.miaopai.com/m/cate2_channel.json?os=android&cateid=124&extend=1&type=news&unique_id=0156a9d2-fb05-3001-83e2-e2592b043531&per=20&token=&page=1&vend=miaopai
    
    //http://api.miaopai.com/m/cate2_channel.json?os=android&cateid=%@&extend=1&udid=0156a9d2-fb05-3001-83e2-e2592b043531&type=news&version=6.3.5&timestamp=1463472565629&unique_id=0156a9d2-fb05-3001-83e2-e2592b043531&per=20&token=&page=1&vend=miaopai
    
        NSString *urlString = [NSString stringWithFormat:@"http://api.miaopai.com/m/cate2_channel.json?cateid=%@&extend=1&type=news&unique_id=0156a9d2-fb05-3001-83e2-e2592b043531&per=20&token=&page=%ld&vend=miaopai", self.categoryId, self.page];
    // 请求分类
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        [self saveData:responseObject DataName:[NSString stringWithFormat:@"%@", self.categoryId]];
        NSDictionary *dic = responseObject;
        NSArray *result = dic[@"result"];
//        self.perContentArr = [NSMutableArray array];
        NSMutableArray *array = [NSMutableArray array];
        for (NSDictionary *temp in result) {
            if ([temp[@"type"] isEqualToString:@"channel"]) {
                AGLChannel *channel = [[AGLChannel alloc] init];
                [channel setValuesForKeysWithDictionary:temp];
                [array addObject:channel];
            } else if ([temp[@"type"] isEqualToString:@"topic"]) {
                AGLTopic *topic = [[AGLTopic alloc] init];
                [topic setValuesForKeysWithDictionary:temp];
                [array addObject:topic];
            }
        }

        if (self.page == 1) {
            self.perContentArr = [NSMutableArray arrayWithArray:array];
        } else {
            [self.perContentArr addObjectsFromArray:array];
        }
        
        self.page += 1;
        // 刷新表格
        [self.perContentCollection.mj_header endRefreshing];
        [self.perContentCollection.mj_footer endRefreshing];
        [self.perContentCollection reloadData];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"首页内容collection联网失败");
        [self.perContentCollection.mj_header endRefreshing];
        [self.perContentCollection.mj_footer endRefreshing];

        NSDictionary *dic = [self getDataWithDataName:[NSString stringWithFormat:@"%@", self.categoryId]];
        if (dic == nil) {
            NSLog(@"请连网啊亲");
        } else {
            NSArray *result = dic[@"result"];
            self.perContentArr = [NSMutableArray array];
            for (NSDictionary *temp in result) {
                if ([temp[@"type"] isEqualToString:@"channel"]) {
                    AGLChannel *channel = [[AGLChannel alloc] init];
                    [channel setValuesForKeysWithDictionary:temp];
                    [self.perContentArr addObject:channel];
                } else if ([temp[@"type"] isEqualToString:@"topic"]) {
                    AGLTopic *topic = [[AGLTopic alloc] init];
                    [topic setValuesForKeysWithDictionary:temp];
                    [self.perContentArr addObject:topic];
                }
            }
            [self.perContentCollection reloadData];
        }
        
        
    }];

    
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
